package nina.yiyou.entry.run

class EntryArgParser {

  interface Arg {

    boolean isFromExcel()

    String getEntryClass()

    List<String> getAppArgs()
  }

  EntryArgParser(String[] args) {
    _args = args
  }

  Arg parse() {
    List<String> appArgs = _args.toList()
    def takeArg = this.&takeArg.curry(appArgs)

    boolean fromExcel = takeArg('--excel', 1)
    String entryClass = takeArg('--entry', 2)[1]

    return new Arg() {
      @Override
      boolean isFromExcel() {
        return fromExcel
      }

      @Override
      String getEntryClass() {
        return entryClass
      }

      @Override
      List<String> getAppArgs() {
        return appArgs
      }
    }
  }

  private List<String> takeArg(List<String> from, String key, int count) {
    int keyIndex = from.indexOf(key)
    if (keyIndex < 0) {
      return []
    }

    int resultEnd = keyIndex + count
    List<String> result = from.subList(keyIndex, resultEnd).collect()
    (resultEnd - 1..keyIndex).each { from.removeAt(it) }

    return result
  }

  private final String[] _args
}
